package com.rotten;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;

import android.os.Environment;
import android.util.Log;

public class Favorites {

	File root = Environment.getExternalStorageDirectory();
	private String dir_favorites = root + "/Android/data/rottenmovies/favorites.txt";
	private String dir_tosee = root + "tosee.txt";
	
	private Vector<Movie> favorites = new Vector<Movie>();
	private Vector<Movie> tosee = new Vector<Movie>();
	
	File f = new File(root + "/Android/data/rottenmovies");
	
	Favorites(){};
	
	public void saveFavorite(final Vector<Movie> favorites) {	
		
		if(!f.exists()){
			Log.v("Tag", "a criar pasta");
			f.mkdirs();
		}
			
		(new Thread(){
			public void run(){
				PrintWriter bw = null;
				Movie mov = null;
				try {
					bw = new PrintWriter(dir_favorites);
					for (int i = 0; i < favorites.size(); ++i) {
						mov = favorites.get(i);
						bw.println(mov.getId() + "///" + mov.getTitle() + "///" + mov.getPoster_thumbnail());
						Log.v("linha gravada:", mov.getId() + "|" + mov.getTitle() + "|" + mov.getPoster_thumbnail());
					}
					bw.flush();
					bw.close();
				} catch (IOException e) {
					System.err.println("Error: " + e.getMessage());
					Log.v("Gravado em:", "ERRO");
				}
			}
		}).start();
	}
	
	public Vector<Movie> getFavorites() {

		Log.v("A ler de:", dir_favorites);
		try {
			Main.favoritos.removeAllElements();
			FileInputStream fstream = new FileInputStream(dir_favorites);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			// Read File Line By Line
			String mov[];
			while ((strLine = br.readLine()) != null) {	
				Movie movie = new Movie();
				mov = strLine.split("///");				
				movie.setId(Integer.parseInt(mov[0]));
				movie.setTitle(mov[1]);
				movie.setPoster_thumbnail(mov[2]);
				favorites.add(movie);
				System.out.println(strLine);
			}
			in.close();
		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
			Log.v("Nao lido:", dir_favorites);
		}

		return favorites;
	}
	
	public Boolean existMovieFavorites(int id){		
		for(int i=0;i<Main.favoritos.size();++i){
			if(Main.favoritos.get(i).getId() == id)
				return true;
		}		
		return false;		
	}
	
	public void removeFavorite(int id){
		for(int i=0;i<Main.favoritos.size();++i){
			if(Main.favoritos.get(i).getId() == id){
				Main.favoritos.remove(i);
				--i;
			}
			
		}
		saveFavorite(Main.favoritos);
	}
	
	
	public static void main(String[] args) {
	
	}
	
}
